/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.brainstretch.service;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import org.brainstretch.ejb.managers.QuizManager;
import org.brainstretch.ejb.managers.UserSessionManager;
import org.brainstretch.models.CompletionStatus;
import org.brainstretch.models.User;
import org.brainstretch.models.UserQuiz;
import org.brainstretch.models.actions.AnswerList;
import org.brainstretch.models.actions.UserAnswer;
import org.brainstretch.models.quizzes.Quiz;
import org.brainstretch.models.quizzes.QuizInstance;

@Path("quiz")
@Stateless
public class QuizService {
    
    @EJB
    QuizManager quizManager;
    
    @EJB
    UserSessionManager userManager;
    
    @GET
    @Produces({"application/json"})
    @Path("take")
    public QuizInstance getQuizInstance(@QueryParam("user") String username, @QueryParam("quizId") long quizId){
        Quiz quiz = quizManager.findById(quizId);      
        User user = userManager.findUserByName(username);
        if(quiz == null){
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }        
        QuizInstance quizInstance = quizManager.getQuizInstanceFor(quiz, user);     
        return quizInstance;   
    }

    @POST
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    @Path("grade")
    public Response gradeAnswers(@QueryParam("user") String username, @QueryParam("quizId") long quizId, @QueryParam("quizToken") String token, AnswerList answers){
        User user = userManager.findUserByName(username);
        UserQuiz quizAction = quizManager.findActionFor(user, token, quizId);
        quizManager.score( answers, quizAction);
        return Response.ok().entity(answers).build();
    }
    
    @POST
    @Consumes("application/json")
    @Produces("applicaiton/json")
    @Path("complete")
    public Response completeQuiz(@QueryParam("user") String username, @QueryParam("quizId") long quizId, @QueryParam("quizToken") String token, CompletionStatus status){
        User user = userManager.findUserByName(username);
        UserQuiz quizAction = quizManager.findActionFor(user, token, quizId);
        quizManager.finishQuiz(quizAction, status);
        AnswerList unanswered = quizManager.getAnswersForUnansweredQuestions(quizAction);
        for(UserAnswer ans: unanswered.getAnswers()){
            System.out.println(ans.getText() + " "+ans.getStatus());
        }
        return Response.ok().entity(unanswered).build();
    }
}
